import { clearAuth, getApiUrl, getAuth, handleUnauthorized } from "./common";
import type { UserInfo } from "./types";

/**
 * 登录
 * @param username
 * @param password
 * @returns
 */
export async function login(
  username: string,
  password: string
): Promise<UserInfo | null> {
  try {
    const url = getApiUrl("/userinfo");
    const res = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: "Basic " + window.btoa(`${username}:${password}`),
      },
    });
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    const data = await res.json();

    if (!data.username) {
      throw new Error("response body error");
    }
    return data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

/**
 * 获取用户信息
 * @returns
 */
export async function getUserInfo(): Promise<UserInfo | null> {
  try {
    const auth = getAuth();
    if(!auth){
      return null;
    }
    const url = getApiUrl("/userinfo");
    const res = await fetch(url, {
      method: "GET",
      headers: {
        Authorization: auth,
      },
    });
    if (res.status === 401) {
      handleUnauthorized(url);
    }
    if (res.status !== 200) {
      throw new Error(`response status error: ${res.status}`);
    }
    const data = await res.json();

    if (!data.username) {
      throw new Error("response body error");
    }
    return data;
  } catch (err) {
    console.error(err);
  }
  return null;
}

/**
 *
 * @returns 登出
 */
export async function logout(): Promise<boolean> {
  const flag = clearAuth()
  return  flag;
}
